// ==UserScript==
// @name       美尧助手
// @namespace    https://gitee.com/yoke/jasmine_btn.git
// @version      0.4
// @description  try to take over the world!
// @author     白板
// @include    http://koms.komect.net/*
// @grant        none
// @require    https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
// @require    https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.2/xlsx.full.min.js
// @require    https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js
// @require    https://cdnjs.cloudflare.com/ajax/libs/async/2.6.2/async.min.js
// ==/UserScript==

console.log('jasmine get url');
(function () {
  'use strict';

  function getPath() {
    return location.href.replace(new RegExp("\\?.*", "gm"), '');
  }

  let lastHref = getPath();
  let nowHref = lastHref;

  $('#koms-app').bind('DOMSubtreeModified', function (e) {
    if (e.target.innerHTML.length > 0) {
      // Content change handler
      nowHref = getPath();
      if (lastHref !== nowHref) {
        lastHref = nowHref;
        loadButton();
      }
    }
  });

  jQuery.fn.wait = function (func, times, interval) {
    var _times = times || -1, //100次
      _interval = interval || 20, //20毫秒每次
      _self = this,
      _selector = this.selector, //选择器
      _iIntervalID; //定时器id
    if (this.length) { //如果已经获取到了，就直接执行函数
      func && func.call(this);
    } else {
      _iIntervalID = setInterval(function () {
        if (!_times) { //是0就退出
          clearInterval(_iIntervalID);
        }
        _times <= 0 || _times--; //如果是正数就 --
        _self = $(_selector); //再次选择
        if (_self.length) { //判断是否取到
          func && func.call(_self);
          clearInterval(_iIntervalID);
        }
      }, _interval);
    }
    return this;
  }


  function loadButton() {
    console.log('jasmine url change');
    console.log(lastHref);

    var komsToken = sessionStorage.getItem("komsToken");

    if (lastHref.endsWith('recruitInform')) {

      // Your code here...
      $('.ivu-breadcrumb-item-link').wait(function () {
        console.log('招聘需求加载成功');
        var btn1 = $("<input type='button' id='testBtn1' value='导出招聘中' class='ivu-btn ivu-btn-default'>");
        this.append(btn1);

        let now = 0;
        let max = 0;
        let dataMap = {}

        function getPage(page) {
          console.log('get page', page)
          $.get("/koms/recruitment/query", { token: komsToken, random: Math.random(), process_status: 190, pageNo: page, limit: 10 },
            function (data) {
              if (page === 1) {
                max = data.recrutimentList.total * 2;
                // max = 20
              }
              if (data.recrutimentList.pages > page) {
                getPage(page + 1);
              }
              let idList = []
              for (let item of data.recrutimentList.list) {
                dataMap[item.id] = item;
                idList.push(item.id);
              }
              getNumber(idList);
              getDetail(idList)
            });
        }
        function getNumber(ids) {
          console.log('get ids', ids)
          //异步控制并发
          async.mapLimit(ids, 10, function (id, callback) {
            $.get("/koms/recruitment/count", { token: komsToken, random: Math.random(), id: id },
              function (data) {
                if (data.code == 200) {
                  Object.assign(dataMap[id], data.result)
                  checkFinish();
                }
              })
          })
        }
        function getDetail(ids) {
          console.log('get getDetail', ids)
          //异步控制并发
          async.mapLimit(ids, 10, function (id, callback) {
            $.get("/koms/recruitment/queryDetail", { token: komsToken, random: Math.random(), id: id },
              function (data) {
                if (data.code == 200) {
                  Object.assign(dataMap[id], data.recrutiment)
                  checkFinish();
                }
              })
          })
        }
        function checkFinish() {
          now++;
          console.log(now, max)
          if (now >= max) {
            let dataList = []
            for (const id in dataMap) {
              dataMap[id]['待招人数'] = dataMap[id]['totalNum']
              dataMap[id]['简历筛选中'] = dataMap[id]['filterNum']
              dataMap[id]['简历通过人数'] = dataMap[id]['interviewPassNum']
              dataMap[id]['面试流程中'] = dataMap[id]['interviewNum']
              dataMap[id]['入池流程中'] = dataMap[id]['intoPoolNum']
              dataMap[id]['已招聘人数'] = dataMap[id]['hireNum']
              delete dataMap[id]['totalNum']
              delete dataMap[id]['process_status']
              delete dataMap[id]['statusName']
              delete dataMap[id]['intoPoolNum']
              delete dataMap[id]['interviewNum']
              delete dataMap[id]['interviewPassNum']
              delete dataMap[id]['filterNum']
              delete dataMap[id]['hireNum']
              dataList.push(dataMap[id])
            }
            dataList.sort(function (a, b) {
              return new Date(b.updateTime) - new Date(a.updateTime)
            })

            var wb = XLSX.utils.book_new();
            var new_ws_name = "SheetJS";
            var ws = XLSX.utils.json_to_sheet(dataList)
            XLSX.utils.book_append_sheet(wb, ws, new_ws_name);

            /* bookType can be any supported output type */
            var wopts = { bookType: 'xlsx', bookSST: false, type: 'array' };

            var wbout = XLSX.write(wb, wopts);

            /* the saveAs call downloads a file on the local machine */
            saveAs(new Blob([wbout], { type: "application/octet-stream" }), "招聘信息.xlsx");
          }
        }

        $("#testBtn1").bind("click", function () {
          getPage(1)
        });
      });
    } else if (lastHref.endsWith('addTalentResume/-1')) {
      // Your code here...
      $('.ivu-breadcrumb-item-link').wait(function () {
        console.log('简历加载成功');

        var btn1 = $('<input type="file" name="xlfile" id="xlf" style="display: inline;"/>');
        $(this[1]).append(btn1);

        var xlf = btn1.get(0);
        if (!xlf.addEventListener) return;
        function handleFile(e) {
          var files = e.target.files, f = files[0];
          var reader = new FileReader();
          reader.onload = function (e) {
            var data = new Uint8Array(e.target.result);
            var workbook = XLSX.read(data, { type: 'array' });

            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            var a = XLSX.utils.sheet_to_json(worksheet, { header: "A" });
            console.log(a)
            fillForm(a)
          };
          reader.readAsArrayBuffer(f);
        }
        xlf.addEventListener('change', handleFile, false);

        const inputEvent = new Event('input')
        const changeEvent = new Event('change')

        function setInputVal(input, val) {
          input.value = val;
          input.dispatchEvent(inputEvent)
        }

        function setDateVal(input, val) {
          input.value = val;
          input.dispatchEvent(changeEvent)
        }

        function setSelectVal(select, val) {
          select.find('.ivu-select-item:contains("' + val + '")').click()
        }

        function indexToColume(index) {
          return "BCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(index);
        }

        function attributeCount(obj) {
          var count = 0;
          for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
              count++;
            }
          }
          return count;
        }

        function fillForm(data) {
          const colume = 'B';
          var inputs = $('.basic_info .ivu-input')
          var selects = $('.basic_info .ivu-select')
          //姓名
          setInputVal(inputs[0], data[1][colume])
          //性别
          setSelectVal(selects.eq(0), data[2][colume])
          //出生日期
          setDateVal(inputs[1], data[3][colume])
          //身份证号
          setInputVal(inputs[2], data[4][colume])
          //手机号码
          setInputVal(inputs[3], data[5][colume])
          //电子邮箱
          setInputVal(inputs[4], data[6][colume])
          //毕业院校
          setInputVal(inputs[5], data[7][colume])
          //最高学历
          setSelectVal(selects.eq(1), data[8][colume])
          //期望工作地点
          setSelectVal(selects.eq(2), data[9][colume])
          //岗位类别
          setSelectVal(selects.eq(3), data[10][colume])
          //职位名称
          // setSelectVal(selects.eq(4), data[2][colume])
          //岗位级别
          setSelectVal(selects.eq(5), data[12][colume])
          //工作年限
          setInputVal($('.basic_info .ivu-input-number-input')[0], data[13][colume])

          //教育
          fillEducation(0);
          //多条
          var count = attributeCount(data[18]) - 2;
          if (count > 0) {
            for (let i = 0; i < count; i++) {
              $('.addExperience').eq(0).click()
              $('.education_experience:eq(' + (i + 1) + ')').wait(function () {
                fillEducation(i + 1)
              })
            }
          }

          //工作
          fillWork(0);
          //多条
          count = attributeCount(data[25]) - 2;
          if (count > 0) {
            for (let i = 0; i < count; i++) {
              $('.addExperience').eq(1).click()
              $('.work_experience:eq(' + (i + 1) + ')').wait(function () {
                fillWork(i + 1)
              })
            }
          }

          //项目
          fillProject(0);
          //多条
          count = attributeCount(data[38]) - 2;
          if (count > 0) {
            for (let i = 0; i < count; i++) {
              $('.addExperience').eq(2).click()
              $('.project_experience:eq(' + (i + 1) + ')').wait(function () {
                fillProject(i + 1)
              })
            }
          }

          //备注信息
          setInputVal($('.ivu-input').last()[0], data[42][colume])

          //教育
          function fillEducation(index) {
            var colume = indexToColume(index)
            inputs = $('.education_experience:eq(' + index + ') .ivu-input');
            selects = $('.education_experience:eq(' + index + ') .ivu-select');
            //起止时间
            setDateVal(inputs[0], data[16][colume] + ' - ' + data[17][colume]);
            //学校名称
            setInputVal(inputs[1], data[18][colume]);
            //专业名称
            setInputVal(inputs[2], data[19][colume]);
            //学历
            setSelectVal(selects.eq(0), data[20][colume]);
          }

          //工作
          function fillWork(index) {
            var colume = indexToColume(index)
            inputs = $('.work_experience:eq(' + index + ') .ivu-input');
            selects = $('.work_experience:eq(' + index + ') .ivu-select');
            //起止时间
            setDateVal(inputs[0], data[23][colume] + ' - ' + data[24][colume]);
            //公司名称
            setInputVal(inputs[1], data[25][colume]);
            //所属行业
            setInputVal(inputs[2], data[26][colume]);
            //公司规模
            setSelectVal(selects.eq(0), data[27][colume]);
            //公司性质
            setSelectVal(selects.eq(1), data[28][colume]);
            //部门名称
            setInputVal(inputs[3], data[29][colume]);
            //职位名称
            setInputVal(inputs[4], data[30][colume]);
            //工作性质
            setSelectVal(selects.eq(2), data[31][colume]);
            //工作描述
            setInputVal(inputs[5], data[32][colume]);
          }

          //项目
          function fillProject(index) {
            var colume = indexToColume(index)
            inputs = $('.project_experience:eq(' + index + ') .ivu-input');
            //起止时间
            setDateVal(inputs[0], data[35][colume] + ' - ' + data[36][colume]);
            //公司名称
            setInputVal(inputs[1], data[37][colume]);
            //项目名称
            setInputVal(inputs[2], data[38][colume]);
            //项目描述
            setInputVal(inputs[3], data[39][colume]);
            //责任描述
            setInputVal(inputs[4], data[40][colume]);
          }
        }

      })
    }
  }

  loadButton();
})();